package com.ht.medicaltreatment.activity

import android.content.Intent
import android.content.res.Configuration
import android.graphics.Color
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.PDOrderDetailAdapter
import com.ht.medicaltreatment.constant.DevicesSDK
import com.ht.medicaltreatment.serial.SerialPortUtils
import com.ht.medicaltreatment.utils.HandDevicesUitls
import com.ht.medicaltreatment.utils.ScanListener
import com.ht.medicaltreatment.utils.ScanUtils
import com.ht.medicaltreatment.utils.SoundUtils
import com.ht.medicaltreatment.viewmodel.InventoryOrderDetailViewModel
import com.xgst.lib.utils.showToast
import kotlinx.android.synthetic.main.activity_pd_detail_layout.btnStart
import kotlinx.android.synthetic.main.activity_pd_detail_layout.recyclerView
import kotlinx.android.synthetic.main.activity_pd_detail_layout.tvCreateName
import kotlinx.android.synthetic.main.activity_pd_detail_layout.tvCreateTime
import kotlinx.android.synthetic.main.activity_pd_detail_layout.tvProgress

//开始盘点，表单详情
class InventoryOrderDetailActivity : BaseActivity(), ScanListener {

    override fun getLayoutId() = R.layout.activity_pd_detail_layout

    private val model by viewModels<InventoryOrderDetailViewModel>()
    private val adapter = PDOrderDetailAdapter()
    private var planId = 0

    override fun init() {
        planId = intent.getIntExtra("id",-1)

        val title = intent.getStringExtra("title")?:"表单名称"
        setTitle(title)

        if(DevicesSDK.devices == DevicesSDK.HAND){
            HandDevicesUitls.init(this)
        }else if (DevicesSDK.devices == DevicesSDK.PDA){
            ScanUtils.init()
        }else if(DevicesSDK.devices == DevicesSDK.ALL_IN_ONE_MACHINE){
            SerialPortUtils.initDevice()
            initListener()
        }

        //开始盘点
        btnStart.setOnClickListener {
            if(btnStart.text.contains("停止")){
                btnStart.text = "开始盘点"
                if(DevicesSDK.devices == DevicesSDK.HAND){
                    HandDevicesUitls.stopScan()
                }else if(DevicesSDK.devices == DevicesSDK.PDA){
                    ScanUtils.close()
                }
            }else{
                startScan()
            }
        }
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter
    }

    override fun onResume() {
        super.onResume()
        initData()
    }

    private fun initData() {
        model.reuqestSampleBox("$planId",{
            adapter.setNewInstance(it.inventorySampleBoxList)
            tvCreateTime.text = "${it.inventoryTable.createTime}"
            tvCreateName.text = "${it.inventoryTable.username}"
            val size = it.inventorySampleBoxList.filter { it.checkStatus == 1 }.size
            tvProgress.text = "$size/${it.inventorySampleBoxList.size}"
            if(size == it.inventorySampleBoxList.size){
                btnStart.isEnabled = false
                btnStart.setBackgroundColor(Color.GRAY)
            }
        })
    }


    fun startScan(){
        btnStart.text = "停止盘点"
        if(DevicesSDK.devices == DevicesSDK.HAND){
           HandDevicesUitls.startScan()
        }else if(DevicesSDK.devices == DevicesSDK.PDA){
            ScanUtils.open { uid ->
                val item = adapter.data.find { it.rfidSampleBox?.rfidCode == uid }
                if(item != null){
                    SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
                    ScanUtils.close()
                    var intent = Intent()
                    if (this.getResources().getConfiguration().orientation ==
                        Configuration.ORIENTATION_PORTRAIT) {
                        //竖屏
                        intent.setClass(this,InventoryScanActivity::class.java)
                    } else {
                        //横屏
                        intent.setClass(this,InventoryScanLandActivity::class.java)
                    }
                    intent.putExtra("uid",uid)
                    intent.putExtra("orderId",planId)
                    startActivityForResult(intent,{
                        initData()
                    })
                    btnStart.text = "开始盘点"
                }else{
                    SoundUtils.playSound(SoundUtils.SOUND_ERROR)
                }
            }
        }else if(DevicesSDK.devices == DevicesSDK.ALL_IN_ONE_MACHINE){
            SerialPortUtils.startHF()
        }
    }

    /**
     * 一体机监听接收到的数据
     */
    private fun initListener() {
        SerialPortUtils.setListener {uid,row,col ->
            LogUtils.i("盘点uid  $uid")
            if(uid.isEmpty()){
                showToast("没有扫描到芯片uid")
                return@setListener
            }
            btnStart.text = "开始盘点"
            SerialPortUtils.close()
            SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
            var intent = Intent(this,InventoryScanLandActivity::class.java)
            intent.putExtra("uid",uid)
            intent.putExtra("orderId",planId)
            startActivityForResult(intent,{
                initData()
            })
        }
    }


    //手持设备扫描结果
    override fun onScan(uid: String) {
        val item = adapter.data.find { it.rfidSampleBox?.rfidCode == uid }
        if(item != null){
            //SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
            HandDevicesUitls.stopScan()
            val intent = Intent(this,InventoryScanActivity::class.java)
            intent.putExtra("uid",uid)
            intent.putExtra("orderId",planId)
            startActivityForResult(intent,{
                initData()
            })
            btnStart.text = "开始盘点"
        }else{
            //SoundUtils.playSound(SoundUtils.SOUND_ERROR)
        }
    }
}
